import cgi
import os
import md5
import string

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template
from google.appengine.api import mail

class Record(db.Model):
  name = db.StringProperty()
  parent_keyname = db.StringProperty(default=None)
  date = db.DateTimeProperty(auto_now_add=True)
  
class ContactInfo(db.Model):
  record = db.ReferenceProperty(Record,collection_name='contact_details')
  contact_detail = db.StringProperty()
  
class Token(db.Model):
  nickname = db.StringProperty()
  contact_number = db.StringProperty()
  email = db.StringProperty()
  

class CreateRecord(webapp.RequestHandler):
  def post(self):
    if self.request.get('record_name') and self.request.get('contact_number'):
        
        record_name = str(self.request.get('record_name'))
        record_list = record_name.split('.')
        record_name = record_list.pop()
        parent_str = string.join(record_list,'.')
        
        if parent_str != "":
          
            parent_record = Record.get_by_key_name(parent_str)
            
            if parent_record != None:
              
                parent_name = str(parent_record.key().name())
                
                fullname = parent_name + record_name
                
                record = Record(key_name=fullname)
                record.name = record_name
                record.parent_keyname = parent_name
                record.put()
                
                contact_info = ContactInfo()
                contact_info.record = record
                contact_info.contact_detail = self.request.get('contact_number')
                contact_info.put()
                
                self.redirect('/?record=' + fullname)
                
            else:
              
                self.redirect('/?error=invalidparent')
        
        else:
          
            fullname = record_name
            
            record = Record(key_name=fullname)
            record.name = record_name
            record.put()
            
            contact_info = ContactInfo()
            contact_info.record = record
            contact_info.contact_detail = self.request.get('contact_number')
            contact_info.put()
            
            self.redirect('/?record=' + fullname)
        
    
    else:
        self.redirect('/')
    


class MainPage(webapp.RequestHandler):
  def get(self):
    template_values = {
          'message': "",
          'contact_number': {},
          }
    if self.request.get('error') and self.request.get('record'):
        if self.request.get('error') == 'notavailable':
            template_values = {
          'message': "Record " + str(self.request.get('record')) + " not available.",
          'contact_number': {},
          }
        else:
            template_values = {
          'message': "Error. Something happened that wasn't supposed to happen, but it happened anyway.",
          'contact_number': {},
          }
    
    elif self.request.get('error'):
        if self.request.get('error') == 'notoken':
            template_values = {
          'message': "Error. Token not available. Either it has expired or it doesn't exist.",
          'contact_number': {},
          }
            
    elif self.request.get('message'):
        if self.request.get('message') == 'sentmail':
            template_values = {
          'message': "A message has been sent to your email. Please check your email. Thank you!",
          'contact_number': {},
          }
        
    elif self.request.get('record'):
        result = Record.get_by_key_name(str(self.request.get('record')))
        if result:
            template_values = {
              'message': result.name,
              'contact_details': result.contact_details,
              }
        else:
            template_values = {
              'message': "Sorry. No Results for " + str(self.request.get('record')),
              'contact_number': {},
              }
    else:
        template_values = {
          'message': "",
          'contact_number': {},
          }
            
    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))
    

class RegForm(webapp.RequestHandler):
  def get(self):
    template_values = {
          'message': ""
          }
    if self.request.get('error'):
        if self.request.get('error') == 'incomplete':
            template_values = {
          'message': "Please fill up all the fields."
          }
            
        elif self.request.get('error') == 'invalidemail':
            template_values = {
          'message': "Error. Email Address provided is invalid. Please provide a valid email."
          }
            
    path = os.path.join(os.path.dirname(__file__), 'regform.html')
    self.response.out.write(template.render(path, template_values))
    
    
class Register(webapp.RequestHandler):
  def get(self):

    if self.request.get('token'):
        token_result = Token.get(str(self.request.get('token')))
        if token_result:
            
            nickname = token_result.nickname
            email = token_result.email
            number = token_result.contact_number
        
            nickname_result = Record.get_by_key_name(nickname)
            if nickname_result:
              
                self.redirect('/?error=notavailable&nickname=' + nickname)
            else:                                
                record = Record(key_name=str(nickname))
                record.nickname = nickname
                record.email = email
                record.contact_number = [number]
                record.put()
                token_result.delete()
                self.redirect('/?nickname=' + str(nickname))
        else:
            self.redirect('/?error=notoken')
    else:
        self.redirect('/?error=notoken')


class Start(webapp.RequestHandler):
  def post(self):
    
    if self.request.get('email') and self.request.get('nickname') and self.request.get('contact_number'):
        user_address = self.request.get('email')
        nickname = str.lower(str(self.request.get('nickname')))
        number = str(self.request.get('contact_number'))
    
        if not mail.is_email_valid(user_address):
            # prompt user to enter a valid address
            self.redirect('/regform?error=invalidemail')
    
        else:
            token = Token()
            token.nickname = nickname
            token.contact_number = number
            token.email = str(user_address)
            token.put()
            token_key = str(token.key())
            confirmation_url = 'http://oped.lutelo.com/register?token=' + token_key
            sender_address = "public.directory.admin@lutelo.com"
            subject = "Okay. You're human. One last step left."
            body = """
    Click the link below to create your directory entry.
    
    %s
    """ % confirmation_url
    
            mail.send_mail(sender_address, user_address, subject, body)
            
            self.redirect('/?message=sentmail')
            
    else:
        self.redirect('/regform?error=incomplete')

        

application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/register', Register),
                                      ('/start', Start),
                                      ('/regform', RegForm),
                                      ('/createrecord', CreateRecord)],
                                     debug=True)

def main():
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
